<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable/>
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable/>
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource" placeholder="单据来源">
          <el-option label="客户订单" :value="1"/>
          <el-option label="库存备货" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.materialCode" placeholder="产品/物料编号" clearable/>
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.materialName" placeholder="产品/物料名称" clearable/>
      </el-form-item>

      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customerCode" placeholder="客户编号" clearable/>
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customerName" placeholder="客户名称" clearable/>
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderType" placeholder="工单类型">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"
          />
        </el-select>
      </el-form-item>
      <!--日期选择器-->
      <el-form-item label="需求时间">
        <el-date-picker
            v-model="searchForm.requestDate"
            type="datetime"
            placeholder="请选择需求时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="MMM DD, YYYY"
            time-format="HH:mm"
            style="width: 200px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button x type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 工具栏 -->
  <div class="toolbar">
    <el-button :icon="Plus" type="primary" @click="handleAdd" plain>新增工单</el-button>
    <el-button :icon="Edit" type="success" @click="handleUpdate" plain>修改</el-button>
    <el-button :icon="Delete" type="danger" @click="handleDelete" plain>删除</el-button>
  </div>
  <!-- 列表 -->
  <el-card class="table-card">
    <el-table
        :data="productionOrderList"
        border
        stripe
        @selection-change="handleSelectionChange"
    >
      <el-table-column prop="productionOrderCode" label="工单编号" min-width="" fixed>
        <template #default="scope">
          <el-link type="primary" @click="handleGetById(scope.row)">{{ scope.row.productionOrderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称" min-width="" fixed/>
      <el-table-column label="工单类型" prop="typeDictData.dictLabel" min-width="" fixed>
        <template #default="scope">
          {{ scope.row.typeDictData?.dictLabel || '未知类型' }}
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderSource" label="来源类型">
        <template #default="scope">
          {{ scope.row.productionOrderSource == 1 ? '客户订单' : '库存备货' }}
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号" fixed/>
      <el-table-column prop="materialCode" label="产品/物料编号" fixed/>
      <el-table-column prop="materialName" label="产品/物料名称" fixed>
        <template #default="{row}">
          {{ row.material?.name ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="material.specification" label="规格" fixed/>
      <el-table-column prop="material.unit.name" label="单位" fixed/>
      <el-table-column prop="productionOrderQuantity" label="工单数量" fixed/>
      <el-table-column prop="productionOrderQuantity" label="已生产数量" fixed>
        {{ 0 }}
      </el-table-column>
      <el-table-column prop="customer.code" label="客户编号" table-fixed="20"/>
      <el-table-column prop="customer.name" label="客户名称"/>
      <el-table-column prop="requestDate" label="需求日期"/>
      <el-table-column prop="statusDictData.dictLabel" label="状态">
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.statusDictData?.dictValue == 1">
            <el-button type="info" text :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" text :icon="Delete"
                       @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
          <template v-if="scope.row.statusDictData?.dictValue == 2">
            <el-button @click="handleAudit(scope.row)"
                       type="default" text :icon="Check">审核
            </el-button>
          </template>
          <template v-if="scope.row.statusDictData.dictValue == 4">
            <el-button type="info" @click="preview(scope.row)"
                       text :icon="Star">预览
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分页栏 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 新增/编辑弹窗 ⬇️-->
  <el-dialog :title="dialogTitle" v-model="addOrUpdateDialogVisable" @close="dialogClose" width="800px">
    <el-form label-width="auto" :model="productionOrderForm" hide-required-asterisk
             show-message="false">
      <el-form-item label="工单编号">
        <el-input v-model="productionOrderForm.productionOrderCode"/>
        <el-switch
            @click="autoCode"
            v-model="isAutoCode"
            size="large"
            inline-prompt
            active-text="自动生成"
            inactive-text="自动生成"/>
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="productionOrderForm.productionOrderName"/>
      </el-form-item>
      <!--来源类型-->
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="来源类型">
            <el-radio-group v-model="productionOrderForm.productionOrderSource">
              <el-radio :label="'客户订单'">客户订单</el-radio>
              <el-radio :label="'库存备货'">库存备货</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- 订单编号（仅客户订单时显示） -->
        <el-col :span="8" v-if="productionOrderForm.productionOrderSource === '客户订单'">
          <el-form-item label="订单编号" prop="orderCode">
            <el-input
                v-model="productionOrderForm.orderCode"
                placeholder="请输入订单编号"/>
          </el-form-item>
        </el-col>
        <!-- 工单类型 -->
        <el-col :span="productionOrderForm.productionOrderSource === '客户订单' ? 8 : 16">
          <el-form-item label="工单类型" prop="productionOrderType">
            <el-select
                v-model="productionOrderForm.productionOrderType"
                placeholder="请选择"
                style="width: 100%;">
              <el-option
                  v-for="dictData in productionOrderTypeDictDataList"
                  :key="dictData.id"
                  :label="dictData.dictLabel"
                  :value="dictData.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--产品编号\产品名称-->
      <el-row :gutter="10">   <!-- gutter 是两列之间的间距 -->
        <el-col :span="12">
          <el-form-item label="产品编号" prop="materialCode">
            <el-input
                v-model="productionOrderForm.materialCode"
                placeholder="请选择产品"
                clearable>
              <template #suffix>
                <el-icon style="cursor: pointer" @click="openProductSelect">
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="materialName">
            <el-input
                v-model="productionOrderForm.materialName"
                placeholder="请选择产品"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <!-- 规格型号 -->
        <el-col :span="12">
          <el-form-item label="规格型号" prop="materialSpecification">
            <el-input
                v-model="productionOrderForm.materialSpecification"
                placeholder="请选择产品"/>
          </el-form-item>
        </el-col>

        <!-- 单位 -->
        <el-col :span="12">
          <el-form-item label="单位" prop="unit.id">
            <el-input
                v-model="productionOrderForm.unitId"
                placeholder="请选择产品"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 工单数量和需求日期 -->
      <el-row :gutter="10">
        <!-- 工单数量 -->
        <el-col :span="12">
          <el-form-item label="工单数量" prop="productionOrderQuantity">
            <el-input-number
                v-model="productionOrderForm.productionOrderQuantity"
                :min="1"
                style="width: 100%;"/>
          </el-form-item>
        </el-col>

        <!-- 需求日期 -->
        <el-col :span="12">
          <el-form-item label="需求日期" prop="requestDate">
            <el-date-picker
                v-model="productionOrderForm.requestDate"
                type="date"
                placeholder="请选择需求日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 客户相关 -->
      <el-row :gutter="10">
        <!-- 客户编码 -->
        <el-col :span="12">
          <el-form-item label="客户编码" prop="customerCode">
            <el-input
                v-model="productionOrderForm.customerCode"
                placeholder="请选择客户编码"
                clearable>
              <template #suffix>
                <el-icon style="cursor:pointer;" @click="showCustomerList">
                  <search/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <!-- 客户名称（条件显示） -->
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input
                v-model="productionOrderForm.customerName"
                placeholder="请输入客户名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 供应商相关 -->
      <el-row :gutter="10">
        <!-- 供应商编码 -->
        <el-col :span="12">
          <el-form-item label="供应商编码" prop="supplierCode">
            <el-input
                v-model="productionOrderForm.supplierCode"
                placeholder="请选择供应商"/>
          </el-form-item>
        </el-col>

        <!-- 供应商名称 -->
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input
                v-model="productionOrderForm.supplierName"
                placeholder="请选择供应商"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="productionOrderForm.remark" placeholder="请输入内容"/>
      </el-form-item>

      <!--BOM组成与物料需求 组合菜单-->
      <template v-if="isEdit">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="BOM组成" name="bom">
            <!-- 工具栏 -->
            <el-row style="margin-bottom:12px">
              <el-button type="primary" :icon="Search">搜索</el-button>
              <el-button :icon="Refresh">刷新</el-button>
            </el-row>
            <!-- 加v-loading绑定加载状态，用户知道在加载 -->
            <el-table
                :data="bomList"
                border
                style="width: 100%"
                v-loading="bomListLoading"
                loading-text="正在加载BOM数据..."
            >
              <el-table-column type="selection" width="55"/>
              <!-- BOM物料组成（子物料编码）：空值显示“无” -->
              <el-table-column label="BOM物料组成" min-width="120">
                <template #default="scope">
                  {{ scope.row.childMaterial?.code || '无' }}
                </template>
              </el-table-column>
              <!-- BOM物料名称：空值显示“无” -->
              <el-table-column label="BOM物料名称" min-width="150">
                <template #default="scope">
                  {{ scope.row.childMaterial?.name || '无' }}
                </template>
              </el-table-column>
              <!-- 规格型号：空值显示“无” -->
              <el-table-column label="规格型号" min-width="120">
                <template #default="scope">
                  {{ scope.row.childMaterial?.specification || '无' }}
                </template>
              </el-table-column>
              <!-- 单位：空值显示“无” -->
              <el-table-column label="单位" min-width="80">
                <template #default="scope">
                  {{ scope.row.unit?.name || '无' }}
                </template>
              </el-table-column>
              <!-- 预计使用量：空值显示0 -->
              <el-table-column label="预计使用量" min-width="100">
                <template #default="scope">
                  {{ scope.row.quantity || 0 }}
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" width="120">
                <template #default="scope">
                  <el-button type="info" text :icon="Edit" @click="BomEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" text :icon="Delete" @click="BomDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--BOM分页-->
            <el-pagination

                v-model:current-page="bomPageNum"
                v-model:page-size="bomPageSize"
                :total="bomTotal"
                layout="total,prev,pager,next"
                @current-change="handleBomPageChange"
               @size-change="handleBomSizeChange" />
          </el-tab-pane>

          <el-tab-pane label="物料需求" name="requirement">
            <!-- 物料需求页面内容 -->
            <el-table :data="requirementList" border>

            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

    </el-form>
    <template #footer>
  <span class="dialog-footer">
    <el-button @click="cancelAddOrUpdate">关闭</el-button>
    <!-- 编辑模式：保存 + 确认 -->
    <template v-if="isEdit">
      <el-button @click="save">保存</el-button>
      <el-button type="primary" @click="submitProductionOrderForm">确认</el-button>
    </template>
    <!-- 新增模式：只有确认 -->
    <template v-if="!isEdit">
      <el-button type="primary" @click="submitProductionOrderForm">确认</el-button>
    </template>
  </span>
    </template>
  </el-dialog>
  <!--新增/编辑弹窗 ⬆️-->
</template>

<script setup>
// 导入必须的内容
import {ref, onMounted, warn} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Refresh
} from '@element-plus/icons-vue'

const buttons = [
  {type: '', text: 'plain'},
  {type: 'primary', text: 'primary'},
  {type: 'success', text: 'success'},
  {type: 'info', text: 'info'},
  {type: 'warning', text: 'warning'},
  {type: 'danger', text: 'danger'},
]

/* ===== BOM组成 ===== */
const bomList = ref([])        // 当前页数据
const bomTotal = ref(0)         // 总条数
const bomPageSize = ref(10)
const bomPageNum = ref(1)
const bomListLoading = ref(false) // 新增：BOM加载状态

/* ===== 物料需求 ===== */
const materialReqList = ref([])
const reqTotal = ref(0)
const reqPageSize = ref(10)
const reqPageNum = ref(1)

const value1 = ref('')  //日期选择器
import {
  getProductionOrderList,
  getAutoCode,
  queryByCode,
  addProductionOrder,
  deleteProductionOrder,
  updateProductionOrder,
  getProductionOrderById,
  getProductionOrderBom
} from "@/api/production-order.js";
// 导入字典相关的API
import {getDictDataList} from "@/api/dictData.js";


// ----- 属性声明 ↓⬇️--------------
// 处理分页大小变化的事件
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  pagination.value.currentPage = 1; //重置为第一页
  handleSearch();
}
// 处理当前页变化的事件
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;//正确更新currentPage
  handleSearch();
}
//关闭窗体的事件
const dialogClose = () => {
  productionOrderForm.value = {};
}
// 工单列表数据
const productionOrderList = ref([])
//选中的用户
const selectedProductOrder = ref([])
const handleSelectionChange = (selection) => {
  selectedProductOrder.value = selection;
}
//修改操作中的展示客户页面
const showCustomerList = () => {
  customerListDialogVisable.value = true;
}

//新增工单弹窗中的搜索按钮操作
function openProductSelect() {
  // 弹出产品选择窗
  console.log('打开产品选择器')
}

// 弹窗的标题
const dialogTitle = ref("新增工单");
// 弹窗标记
const addOrUpdateDialogVisable = ref(false);
// 编辑标记
const isEdit = ref(false);

// 是否自动生成编号标记
const isAutoCode = ref(false);
// 是否显示详情的标记
const isDetail = ref(false);
// 工单类型字典列表
const productionOrderTypeDictDataList = ref([]);
// 工单状态点列表
const productionOrderStatusDictDataList = ref([]);
// ----- 属性声明 ↑⬆️

// -- 函数声明 ↓

//根据工单Id查询工单信息
const handleGetById = async (productionOrder) => {
  dialogTitle.value = "查看工单信息"
  addOrUpdateDialogVisable.value = true;
  isEdit.value = true
  const res = await getProductionOrderById(productionOrder.id) // 查工单完整信息（含material）
  if (res.code == 200) {
    productionOrderForm.value = res.data
    // 关键：从工单中提取“父物料ID”（res.data.material.id）
    const parentMaterialId = res.data.material?.id;
    if (!parentMaterialId) { // 防止工单未关联物料的情况
      ElMessage.warning("当前工单未关联物料，无法加载BOM");
      return;
    }
    await loadBom(parentMaterialId) // 正确：传父物料ID
    await loadMaterialReq(res.data.id)
  }
}

/* 查询BOM组成*/
async function loadBom(parentMaterialId) { // 参数名改为parentMaterialId（清晰）
  bomListLoading.value = true; // 开始加载（显示loading动画）
  try {
    const params = {
      parentId: parentMaterialId, // 明确传父物料ID
      pageNum: bomPageNum.value,
      pageSize: bomPageSize.value
    }
    const res = await getProductionOrderBom(params)
    // 清晰日志：方便你看是否传对参数、后端是否返回数据
    console.log('【BOM查询】传往后端的父物料ID：', parentMaterialId)
    console.log('【BOM查询】接口入参：', params)
    console.log('【BOM查询】后端返回数据：', res.data)

    if (res.code === 200) {
      bomList.value = res.data.list ?? []
      bomTotal.value = res.data.total ?? 0
      // 无数据提示（用户知道是没配置BOM，不是bug）
      if (bomList.value.length === 0) {
        ElMessage.info(`当前物料（ID：${parentMaterialId}）未配置BOM`);
      }
    } else {
      ElMessage.error(`加载BOM失败：${res.message || '未知错误'}`);
    }
  } catch (err) {
    ElMessage.error(`BOM加载异常：${err.message}`);
  } finally {
    bomListLoading.value = false; // 结束加载（无论成功/失败）
  }
}

const loadProductionOrderStatusDictDataList = () => {
  getDictDataList({dictType: "PRODUCTION_ORDER_STATUS"}).then(res => {
    productionOrderStatusDictDataList.value = res.data.records;
  })
}

//BOM操作中的删除编辑按钮
//编辑按钮
const BomEdit = () => {

}
//删除
const BomDelete = () => {

}


// BOM分页：当前页变化时重新加载
const handleBomPageChange = (newPage) => {
  bomPageNum.value = newPage;
  // 从工单表单中取父物料ID（确保分页传对参数）
  const parentMaterialId = productionOrderForm.value.material?.id;
  if (parentMaterialId) {
    loadBom(parentMaterialId);
  }
}

// BOM分页：每页条数变化时重新加载（重置为第1页）
const handleBomSizeChange = (newSize) => {
  bomPageSize.value = newSize;
  bomPageNum.value = 1; // 条数变了，回到第1页
  const parentMaterialId = productionOrderForm.value.material?.id;
  if (parentMaterialId) {
    loadBom(parentMaterialId);
  }
}
// 加载工单类型字典的函数
const loadProductOrderDictDataList = () => {
  getDictDataList({dictType: "PRODUCTION_ORDER_TYPE"}).then(res => {
    if (res.code === 200 && res.data && res.data.records) {
      productionOrderTypeDictDataList.value = res.data.records;
    } else {
      ElMessage.warning('工单类型字典数据加载失败');
    }
  }).catch(err => {
    ElMessage.error('加载工单类型字典出错: ' + err.message);
  })
}
// 提交新增工单的按钮事件
const submitProductionOrderForm = async () => {
// 1. 手动校验
  if (!productionOrderForm.value.productionOrderCode.trim()) {
    ElMessage.warning('请输入工单编号')
    return
  }
  if (!productionOrderForm.value.productionOrderName.trim()) {
    ElMessage.warning('请输入工单名称')
    return
  }
  if (!productionOrderForm.value.productionOrderType) {
    ElMessage.warning('请选择工单类型')
    return
  }
  if (productionOrderForm.value.productionOrderSource === 1) {
    if (!productionOrderForm.value.orderCode.trim()) {
      ElMessage.warning('请输入订单编号')
      return
    }
    if (!productionOrderForm.value.customerCode.trim()) {
      ElMessage.warning('请输入客户编号')
      return
    }
  }
  if (['外协', '外购'].includes(productionOrderForm.value.productionOrderType)) {
    if (!productionOrderForm.value.supplierCode.trim()) {
      ElMessage.warning('请输入供应商编号')
      return
    }
  }
  // 2. 调接口
  try {
    const api = isEdit.value ? updateProductionOrder : addProductionOrder
    await api(productionOrderForm.value);
    ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
    addOrUpdateDialogVisable.value = false
    handleSearch()          // 刷新列表
  } catch (e) {
    ElMessage.error(e?.message || '操作失败')
  }
}
//save保存按钮
const save = () => {
  /* 1. 先校验 */
  if (!productionOrderForm.value.productionOrderCode) {
    ElMessage.warning("工单编号不能为空");
    return;
  }
  if (!productionOrderForm.value.productionOrderName) {
    ElMessage.warning("工单名称不能为空");
    return;
  }
  if (!productionOrderForm.value.productionOrderType) {
    ElMessage.warning("工单类型不能为空");
    return;
  }
  /* 2. 调接口 */
  try {
    updateProductionOrder(productionOrderForm.value);
    /* 3. 提示 & 关闭 */
    ElMessage.success("保存成功");
    addOrUpdateDialogVisable.value = false;
    handleSearch();
  } catch (e) {
    ElMessage.error(e?.message || "保存失败");
  }
};
// 取消新增/编辑的事件
const cancelAddOrUpdate = () => {
  addOrUpdateDialogVisable.value = false;
}
// 自动生成编号的事件
const autoCode = () => {
  if (isAutoCode.value) {
    // 生成编号
    getAutoCode().then(res => {
      if (res.code == 200) {
        productionOrderForm.productionOrderCode = res.data;
      } else {
        isAutoCode.value = false;
        ElMessage.error("编号自动生成失败")
      }
    })
  } else {
    processForm.processCode = "";
  }
}
// 搜索数据的事件
const handleSearch = () => {
  // 调用查询的接口查询数据
  const params = {
    ...searchForm.value,
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  }
  getProductionOrderList(params).then(res => {
    productionOrderList.value = res.data.list
    pagination.value.total = res.data.total
  }).catch(err => {
    ElMessage.error('加载数据失败：' + err.message);
  })
}
// 工具栏新增工单的按钮事件
const handleAdd = () => {
  dialogTitle.value = "新增工单";
  isEdit.value = false;
  isDetail.value = false;
  // 重置表单数据
  productionOrderForm.id = null;
  productionOrderForm.productionOrderCode = "";
  productionOrderForm.productionOrderName = "";
  productionOrderForm.productionOrderSource = 1;
  productionOrderForm.orderCode = "";
  productionOrderForm.productionOrderType = "";
  productionOrderForm.materialCode = "";
  productionOrderForm.materialName = "";
  productionOrderForm.materialSpecification = "";
  productionOrderForm.unitId = "";
  productionOrderForm.productionOrderQuantity = 1;
  productionOrderForm.requestDate = "";
  productionOrderForm.customerCode = "";
  productionOrderForm.customerName = "";
  productionOrderForm.supplierCode = "";
  productionOrderForm.supplierName = "";
  productionOrderForm.remark = "";

  isAutoCode.value = false;
  addOrUpdateDialogVisable.value = true;
}
//对话框相关
const dialogVisible = ref(false)
//操作栏中的编辑按钮事件
const handleEdit = (order) => {
  dialogTitle.value = '修改生产工单'
  addOrUpdateDialogVisable.value = true
  isEdit.value = true;
  // 异步接口回调内执行loadBom，确保拿到material数据
  getProductionOrderById(order.id).then(res => {
    if (res.code == 200) {
      productionOrderForm.value = res.data;
      // 提取父物料ID
      const parentMaterialId = res.data.material?.id;
      if (!parentMaterialId) {
        ElMessage.warning("当前工单未关联物料，无法加载BOM");
        return;
      }
      loadBom(parentMaterialId); // 正确：传父物料ID（异步顺序对）
    }
  });
}
// 新增/编辑表单的数据绑定对象
const productionOrderForm = ref({
  id: null,
  productionOrderCode: "",
  productionOrderName: "",
  productionOrderSource: 1, // 默认客户订单
  orderCode: "",
  productionOrderType: "",
  materialCode: "",
  materialName: "",
  materialSpecification: "",
  unitId: "",
  productionOrderQuantity: 1,
  requestDate: "",
  customerCode: "",
  customerName: "",
  supplierCode: "",
  supplierName: "",
  remark: ""
});
//操作栏中的审核按钮事件
const handleAudit = (row) => {
  ElMessageBox.confirm(
      '确定要审核这个工单吗?',
      '确认审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(() => {
    // 假接口，后端数据库不变化
    row.statusDictData.dictValue = 3
    row.statusDictData.dictLabel = '已审核'
    ElMessage.success('审核成功')
  }).catch(() => {
    ElMessage.info('已取消审核')
  })
}
//审核按钮操作事件
const preview = (productionOrder) => {
  dialogTitle.value = '审核工单信息'
  addOrUpdateDialogVisable.value = true;

  getProductionOrderById(productionOrder.id).then(res => {
    if (res.code == 200) {
      productionOrderForm.value = res.data;
    }
  })
}
//操作栏中删除工单的事件--草稿状态的工单可以直接删除
const handleDelete = (row) => {
  //先判断状态
  if (row.statusDictData?.dictValue === 1) {
    ElMessage.warning('仅草稿状态可删除')
    return
  }
  ElMessageBox.confirm('确定要删除这个工单吗?', '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
    try {
      await deleteProductionOrder(row.id)
      ElMessage.success('删除成功');
      handleSearch()
    } catch (e) {
      ElMessage.error(e?.message || '删除失败')
    }
  }).catch(() => {
    //取消删除
    ElMessage.success('取消删除')
  })
}

//重置搜索表单
const resetSearch = () => {
//重置所有表单的所有字段为空
  searchForm.value = {
    productionOrderCode: '',
    productionName: '',
    orderCode: '',
    materialCode: '',
    materialName: '',
    customerCode: '',
    productionOrderType: '',
    requestDate: ''
  }
}
// 绑定搜索表单的数据
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  materialCode: "",
  materialName: "",
  customerCode: "",
  customerName: "",
  productionOrderType: "",
  productionOrderSource: "",
  status: "",
  requestDate: []
})

//分页
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})


// -- 函数声明 ↑
onMounted(() => {
  loadProductionOrderStatusDictDataList();
  loadProductOrderDictDataList();
  handleSearch();
})


</script>

<style scoped>

.customer-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>